import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.从请求中获取到用户名和密码
        req.setCharacterEncoding("utf-8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(username==null || username.equals(" ") || password==null || " ".equals(password)){
            //用户名密码为空，直接返回登录失败
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("登录失败");
            return;
        }
        //2.查询数据库，验证用户名密码是否正确
        UserDao userDao=new UserDao();
        User user=userDao.selectByName(username);
        if(user==null || !user.getPassword().equals(password)){
            //用户名不存在
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("登录失败");
            return;
        }
        //3.如果正确，创建一个会话对象
        HttpSession session=req.getSession(true);
        session.setAttribute("user",user);
        //4.构造302响应报文
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用这个方法来针对当前登录状态进行判定
        //1.获取一下当前的会话
        HttpSession session=req.getSession(false);
        if(session==null){
            //没有会话，是未登录状态
            resp.setStatus(403);
            return;
        }
        User user=(User)session.getAttribute("user");
        if(user==null){
            //未登录，无user对象
            resp.setStatus(403);
            return;
        }
        //返回200的相应
        resp.setStatus(200);
    }
}
